<!-- 页面上面部分固定高度，下面部分可以滚动 -->
<template lang="pug">
div
  div(ref="fixed")
    slot(name="fixed")
  div(:style="{height: scrollHeight, overflow: overflow}")
    slot(name="scroll")
  div(ref="fixedBottom")
    slot(name="fixed-bottom")
</template>

<script>
export default {
  name: "FixedScroll",
  props: {
    // 减去的页面底部的高度，主要为了处理底部有tab区域
    minusBottomHeight: {
      type: Number,
      default: 0,
    },
    addScroll: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    let overflow = ""
    if (this.addScroll) {
      overflow = "auto"
    }
    return {
      overflow,
      scrollHeight: "0",
      fixedHeight: 0,
      fixedBottomHeight: 0,
      clientHeight: 0,
      lastMinusHeight: 0,
    }
  },

  methods: {
    refresh() {
      let fixed = this.$refs.fixed.getBoundingClientRect()
      let fixedBottom = this.$refs.fixedBottom.getBoundingClientRect()
      if (fixed.height === this.fixedHeight &&
          fixedBottom.height === this.fixedBottomHeight &&
          this.lastMinusHeight === this.minusBottomHeight &&
          this.clientHeight === document.documentElement.clientHeight
      ) {
        return
      }

      this.fixedHeight = fixed.height
      this.fixedBottomHeight = fixedBottom.height
      this.lastMinusHeight = this.minusBottomHeight
      this.clientHeight = document.documentElement.clientHeight

      /* if (this.clientHeight <= 0) {
        this.clientHeight = document.documentElement.clientHeight
      } */
      this.scrollHeight = `${this.clientHeight - this.minusBottomHeight - this.fixedHeight - fixedBottom.height}px`
    },
  },

  updated() {
    this.refresh()
  },

  mounted() {
    this.refresh()
    window.addEventListener("resize", this.refresh)
  },

  beforeDestroy() {
    window.removeEventListener("resize", this.refresh)
  }
}
</script>

<style lang="stylus" scoped>

</style>
